package com.jahe.learn.netty4.websocket;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.PingWebSocketFrame;
import io.netty.handler.codec.http.websocketx.PongWebSocketFrame;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import io.netty.util.CharsetUtil;
import io.netty.util.concurrent.GlobalEventExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.ByteBuffer;

/**
 * websocket Server 端 消息处理器
 * @author: jahe.lai
 * @create: 2019-12-25 17:22
 */
public class WebSocketFrameHandler extends SimpleChannelInboundHandler<WebSocketFrame> {

    protected static Logger logger = LoggerFactory.getLogger(WebSocketFrameHandler.class);

    private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);


    @Override
    protected void channelRead0(ChannelHandlerContext ctx, WebSocketFrame webSocketFrame) throws Exception {
        if (webSocketFrame instanceof TextWebSocketFrame) {

            TextWebSocketFrame frame = (TextWebSocketFrame)webSocketFrame;
            logger.info("{} textMsg：{} ", ctx.channel().remoteAddress(), frame.text());
            ctx.channel().writeAndFlush(new TextWebSocketFrame("from server "+frame.text()));

        } else if (webSocketFrame instanceof PingWebSocketFrame) {
            // ping 协议会被前置处理了？！  到不了这里。
            logger.warn("PingWebSocketFrame--> " + webSocketFrame);

            ByteBuf buffer = Unpooled.copiedBuffer("PONG", CharsetUtil.UTF_8);
            ctx.channel().writeAndFlush(new PongWebSocketFrame(buffer));

        } else {
            logger.warn("收到消息2--> " + webSocketFrame);
        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
        channelGroup.add(ctx.channel());
        logger.warn("channelGroup size: {}", channelGroup.size());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
        logger.warn("连接断开--> {}  channelGroup size: {}", ctx.channel().remoteAddress(), channelGroup.size());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.channel().close();
    }
}
